package com.hn.message;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hn.Entry.*;
import com.hn.common.ShareData;
import com.hn.utils.http.HttpUtil;
import com.hn.utils.http.ImageUtil;
import com.hn.utils.http.CatApiUtil;
import com.hn.utils.random.RandomUtil;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.*;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.MessageReceipt;
import net.mamoe.mirai.message.data.*;

import java.io.*;
import java.net.URL;
import java.time.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import net.mamoe.mirai.utils.ExternalResource;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

public class CatSendMessage {
    //处理初始数据
    public static Map<String,String> getMatcher(@NotNull GroupMessageEvent event){
        Map<String, String> map=new HashMap<>();
        try {
            String text = event.getMessage().get(0).toString();
            String regex = "mirai:source:ids=\\[(.*?)\\], internalIds=\\[(.*?)\\], from group (.*?) to (.*?) at (.*?)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                map.put("源ID", matcher.group(1));
                map.put("内部ID", matcher.group(2));
                map.put("来源QQ号", matcher.group(3));
                map.put("目标组ID", matcher.group(4));
                map.put("时间戳", matcher.group(5));
            }
        }catch (Exception e){
            System.out.println("获取指令信息失败:"+e.getMessage());
        }
        return map;
    }
    //判断当前QQ号是不是在群老婆列表中
    public static MarryEntry IfWife(Long qq){
        ShareData instance = ShareData.getInstance();
        //获取群老婆列表
        LinkedHashMap<Long, Long> map = instance.getMarryMap();
        for (Long key : map.keySet()) {
            Long value = map.get(key);
            if (key.equals(qq) || value.equals(qq)){
                return MarryEntry.builder()
                        .HusbandId(key)
                        .WifeId(value)
                        .build();
            }
        }
        //此人没有老婆 或 老公
        return null;
    }
    //发送自己当老婆的信息
    public static void sentMarryMessageBySelf(@NotNull GroupMessageEvent event, Long husbandId, Long wifeId){
        //获取老公照片
        String qqImage = HttpUtil.getQQImage(husbandId, event);
        Group group = event.getGroup();
        //获取老公
        NormalMember husBand = group.get(husbandId);
        String husBandName=null;
        if (husBand!=null){
            husBandName = husBand.getNick();
        }else{
            husBandName = husbandId.toString();
        }
        //构建消息
        MessageChain singleMessages = new MessageChainBuilder()
                .append(new At(wifeId))
                .append(new PlainText(" 你被娶了,你的群老公是: "))
                .append(new PlainText(husBandName))
                .append(Image.fromId(qqImage))
                .build();
        event.getSubject().sendMessage(singleMessages);
    }
    //发送自己当老公信息
    public static void sentHusbandMessageBySelf(@NotNull GroupMessageEvent event, Long husbandId, Long wifeId){
        //获取老婆照片
        String qqImage = HttpUtil.getQQImage(wifeId, event);
        Group group = event.getGroup();
        //获取妻子
        NormalMember Wife = group.get(wifeId);
        String wifeName=null;
        if (Wife!=null){
            wifeName = Wife.getNick();
        }else{
            wifeName = wifeId.toString();
        }
        //构建消息
        MessageChain singleMessages = new MessageChainBuilder()
                .append(new At(husbandId))
                .append(new PlainText(" 你的群老婆是: "))
                .append(new PlainText(wifeName))
                .append(Image.fromId(qqImage))
                .build();
        event.getSubject().sendMessage(singleMessages);
    }
    //获取所有群友信息列表
    public static List<Long> getContactList(@NotNull GroupMessageEvent event){
        //群友信息
        ContactList<NormalMember> members = event.getGroup().getMembers();
        //群友QQ号列表
        List<Long> memberList=new ArrayList<>();
        for (NormalMember member:members){
            //最后发言的时间单位为秒
            int lastSpeakTimestamp = member.getLastSpeakTimestamp();
            OffsetDateTime offsetDateTime  = OffsetDateTime.ofInstant(Instant.ofEpochSecond(lastSpeakTimestamp), ZoneId.systemDefault());
            ZonedDateTime zonedDateTime = offsetDateTime.atZoneSameInstant(ZoneId.systemDefault());
            //最后一次发言必须在一天以内 是就添加
            if (zonedDateTime.toLocalDate().isEqual(LocalDate.now())){
                //获取群友QQ号
                long id = member.getId();
                //添加进集合
                memberList.add(id);
            }
        }
        return memberList;
    }
    /**
     * 发送当小三成功的信息
     */
    public static void sentMistressMessage(@NotNull GroupMessageEvent event, Long husbandId, Long wifeId,Long fromQQ){
        Group group = event.getGroup();
        //变成了别人老公
        if (fromQQ.equals(husbandId)){
            //获取妻子
            NormalMember Wife = group.get(wifeId);
            if (Wife==null){
                event.getSender().sendMessage("QQ信息获取失败!!!");
                return;
            }
            //获取老婆名称
            String wifeName = Wife.getNick();
            //获取老婆照片
            String qqImage = HttpUtil.getQQImage(wifeId, event);
            //构建消息
            MessageChain singleMessages = new MessageChainBuilder()
                    .append(new At(fromQQ))
                    .append(new PlainText(" 当小三成功,你的群老婆是: "))
                    .append(new PlainText(wifeName))
                    .append(Image.fromId(qqImage))
                    .build();
            event.getSubject().sendMessage(singleMessages);
        }else {
            //变成别人老婆
            NormalMember husBand = group.get(husbandId);
            if (husBand==null){
                event.getSender().sendMessage("Id获取失败!!!");
                return;
            }
            //获取老公名称
            String husBandName = husBand.getNick();
            //变成了别人老婆
            //获取老公照片
            String qqImage = HttpUtil.getQQImage(husbandId, event);
            //构建消息
            MessageChain singleMessages = new MessageChainBuilder()
                    .append(new At(fromQQ))
                    .append(new PlainText(" 当小三成功,你的群老公是: "))
                    .append(new PlainText(husBandName))
                    .append(Image.fromId(qqImage))
                    .build();
            event.getSubject().sendMessage(singleMessages);
        }
    }

    /**
     * 获取订婚需要的数据
     */
    public static Map<String,String> getEngage(@NotNull GroupMessageEvent event) {
        Map<String,String> map=new HashMap<>();
        if (event.getMessage().size()<2){
            return null;
        }
        String content = event.getMessage().get(2).toString();
        content = content.substring(1, content.length() - 1);  // 去除方括号
        String[] parts = content.split(":");  // 使用冒号作为分隔符
        if (parts.length>=2){
            map.put("type",parts[1]);
            map.put("qq",parts[2]);
            return map;
        }else {
            return null;
        }
    }
    //处理是否有老婆 是老公 是老婆
    public static void handleMarry(GroupMessageEvent event,MarryEntry marryEntry,List<Long> contactList,Long fromQQ){
        if (marryEntry==null){
            //没有老婆 或 老公 开始选老婆
            //统计数 每次为符合就+1 到达5次后 返回未娶到
            int count=0;
            while (true){
                if (count>=5){
                    event.getGroup().sendMessage("暂时没有合适对象,请稍后再试....");
                    break;
                }
                //获取随机数
                int randomNum = RandomUtil.RandomNumberByNext(contactList.size());
                //获得老婆QQ号
                Long wifeId = contactList.get(randomNum);
                //别人有老婆 或 老公 重新选
                if (IfWife(wifeId)==null){
                    //不能娶自己
                    if (!fromQQ.equals(wifeId)){
                        //添加到婚姻登记处
                        ShareData.getInstance().getMarryMap().put(fromQQ,wifeId);
                        sentHusbandMessageBySelf(event,fromQQ,wifeId);
                        return;
                    }
                }
                count++;
            }
        } else if (marryEntry.getHusbandId().equals(fromQQ)){
            //自己是老公
            sentHusbandMessageBySelf(event, marryEntry.getHusbandId(), marryEntry.getWifeId());
        } else if (marryEntry.getWifeId().equals(fromQQ)) {
            //自己是老婆
            sentMarryMessageBySelf(event,marryEntry.getHusbandId(), marryEntry.getWifeId());
        }
    }
    //发送服务器信息
    public static void sendAddressMessage(List<ServerEntry> projectZomboidList, Map<String, String> addresses, GroupMessageEvent event){
        if (projectZomboidList.isEmpty()){
            event.getGroup().sendMessage("暂无服务器信息");
            return;
        }
        //构建消息链
        MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
        messageChainBuilder.append("======服务器信息======\n");
        for (Map.Entry<String, String> entry : addresses.entrySet()) {
            //获取服务器名称
            String address = entry.getValue();
            //如果没有就进入
            if (!isAddress(projectZomboidList, address)) {
                messageChainBuilder.append("无").append(entry.getKey()).append("信息").append("\n");
                messageChainBuilder.append("=====================" + "\n");
                continue;
            }
            //拥有服务器信息
            for (ServerEntry item : projectZomboidList) {
                if (item.getAddr().equals(address)) {
                    String[] Addr = item.getAddr().split(":");
                    String ip = Addr[0];
                    String port = Addr[1];
                    messageChainBuilder.add("\"" + item.getName() + "\"," + "\"" + item.getPlayers() + "/" + item.getMax_players() + "\"\n");
                    messageChainBuilder.append("IP:").append(ip).append(" 端口:").append(port).append("\n");
                    messageChainBuilder.append("=====================\n");
                    break;
                }
            }
        }
        //拼接底部
        messageChainBuilder.append("可以使用域名www.pzmiao.com代替IP\n");
        messageChainBuilder.append("服务器届时会显示未响应但不影响进游戏\n");
        messageChainBuilder.append("=====================\n");
        //获取图片
        String image = ImageUtil.getImage("/root/mirai/image/miaomiao.jpg", event);
        if (image != null) {
            messageChainBuilder.append(Image.fromId(image));
        }
        //发送服务器信息
        MessageChain messages = messageChainBuilder.build();
        event.getGroup().sendMessage(messages);
    }
    //查看服务器是否存在
    public static boolean isAddress(List<ServerEntry> projectZomboidList, String Ip){
        for (ServerEntry serverEntry : projectZomboidList) {
            if (serverEntry.getAddr().equals(Ip) && !serverEntry.getVersion().equals("-1")){
                return true;
            }
        }
        return false;
    }
    //娶群友
    public static void Marry(@NotNull GroupMessageEvent event){
        //起始信息
        Map<String, String> matcher = getMatcher(event);
        //群友QQ列表
        List<Long> contactList = getContactList(event);
        //发起者QQ号
        Long fromQQ= Long.valueOf(matcher.get("来源QQ号"));
        MarryEntry marryEntry = IfWife(fromQQ);
        handleMarry(event,marryEntry,contactList,fromQQ);
    }

    /**
     * 订婚
     */
    public static void Engage(GroupMessageEvent event) {
        ShareData instance = ShareData.getInstance();
        Map<String, String> engage = getEngage(event);
        //参数不符
        if (engage == null) {
            return;
        }
        //起始信息
        Map<String, String> matcher = getMatcher(event);
        //发起者QQ号
        Long fromQQ = Long.valueOf(matcher.get("来源QQ号"));
        //被求婚者QQ
        Long qq = Long.valueOf(engage.get("qq"));
        //看看发起者有没有老婆 或 老婆
        MarryEntry marryEntry = IfWife(fromQQ);
        if (marryEntry != null) {
            event.getGroup().sendMessage("你已经有对象了,不能招花惹草了...");
            return;
        }
        //看看订婚的对象是不是自己
        if (fromQQ.equals(qq)) {
            event.getGroup().sendMessage("自己不能订婚自己,你以为自己就是老婆吗?");
            return;
        }
        //看看被请求者有没有老公 或 老婆
        MarryEntry BymarryEntry = IfWife(qq);
        if (BymarryEntry != null) {
            event.getGroup().sendMessage("别人已经有对象了,不能破坏别人的幸福生活...");
            return;
        }
        //如果进入 则两方没有老婆
        //判断他今天有没有求婚
        List<Long> dingHunList = instance.getDingHunList();
        for (Long item : dingHunList) {
            if (item.equals(fromQQ)) {
                event.getGroup().sendMessage("最近订过婚过哦,不要太花心哦...");
                return;
            }
        }
        //判断类型是不是@ 不是则不处理
        if (engage.get("type").equals("at")) {
            Random rand = new Random();
            int result = rand.nextInt(100);  // 生成0-99的随机数
            boolean isTrue = instance.getManager().contains(event.getSender().getId());
            if (result < 50 || isTrue) {
                //添加到老婆列表中
                instance.getMarryMap().put(fromQQ, qq);
                //发送娶老婆信息
                sentHusbandMessageBySelf(event, fromQQ, qq);
            } else {
                event.getGroup().sendMessage("求婚失败了...");
            }
            //添加到求婚列表
            if (!isTrue) instance.getDingHunList().add(fromQQ);
        }
    }

    /**
     * 离婚
     */
    public static void Divorce(GroupMessageEvent event) {
        ShareData instance = ShareData.getInstance();
        //起始信息
        Map<String, String> matcher = getMatcher(event);
        //发起者QQ号
        Long fromQQ= Long.valueOf(matcher.get("来源QQ号"));
        //看看发起者有没有老婆 或 老婆
        MarryEntry marryEntry = IfWife(fromQQ);
        //查看是否今天离过婚
        List<Long> liHunList = instance.getLiHunList();
        for (Long id:liHunList){
            if (id.equals(fromQQ)){
                event.getGroup().sendMessage("你最近离过婚哦,不可以再离婚了...");
                return;
            }
        }
        if (marryEntry!=null){
            //随机函数
            Random rand = new Random();
            int result = rand.nextInt(100);  // 生成0-99的随机数
            boolean isTrue = instance.getManager().contains(event.getSender().getId());
            if (result < 50 || isTrue) {
                //删除本地存储的结婚
                LinkedHashMap<Long, Long> marryMap = instance.getMarryMap();
                //丈夫ID
                Long husbandId = marryEntry.getHusbandId();
                marryMap.remove(husbandId);
                event.getGroup().sendMessage("离婚成功...");
            } else {
                //是老公
                if (marryEntry.getHusbandId().equals(fromQQ)){
                    event.getGroup().sendMessage("渣男,你老婆这么好,你竟然要离婚...");
                }else{
                    event.getGroup().sendMessage("渣女,你老公这么棒,你竟然要离婚...");
                }
            }
            //添加到离婚列表
            if(!isTrue)instance.getLiHunList().add(fromQQ);
        }else {
            event.getGroup().sendMessage("你还没有对象,快去娶一个吧...");
        }
    }

    /**
     * 当小三
     */
    public static void Mistress(GroupMessageEvent event) {
        ShareData instance = ShareData.getInstance();
        Map<String, String> engage = getEngage(event);
        //参数不符
        if (engage==null){
            return;
        }
        //起始信息
        Map<String, String> matcher = getMatcher(event);
        //发起者QQ号
        Long fromQQ= Long.valueOf(matcher.get("来源QQ号"));
        //被求婚者QQ
        Long qq = Long.valueOf(engage.get("qq"));
        if (fromQQ.equals(qq)){
            event.getGroup().sendMessage("不能当自己小三...");
            return;
        }
        //看看发起者有没有老婆 或 老公
        MarryEntry marryEntry = IfWife(fromQQ);
        //看看被发起者有没有老婆 或 老公
        MarryEntry marry = IfWife(qq);
        //查看是否今天当过小三
        List<Long> List = instance.getXiaoSanList();
        if (List.contains(fromQQ)){
            event.getGroup().sendMessage("你最近当过小三了,不可以再当了...");
            return;
        }
        //当被发起者没有老婆或老公
        if (marry==null){
            event.getGroup().sendMessage("他还没有对象,快去追求吧...");
            return;
        }
        if (marryEntry!=null){
            if (marryEntry.getHusbandId().equals(fromQQ)){
                event.getGroup().sendMessage("你已经有老婆了,不能去当牛头人了...");
            }else {
                event.getGroup().sendMessage("你已经有老公了,不能去当牛头人了...");
            }
            return;
        }

        //随机函数
        Random rand = new Random();
        int result = rand.nextInt(100);  // 生成0-99的随机数
        boolean isTrue = instance.getManager().contains(event.getSender().getId());
        if (result <= 10 || isTrue) {
            //当前@对象是老公身份
            if (marry.getHusbandId().equals(qq)){
                //移除民政局信息
                instance.getMarryMap().remove(marry.getHusbandId());
                instance.getMarryMap().put(qq,fromQQ);
                sentMistressMessage(event,qq,fromQQ,fromQQ);
            }else{
                //当前@对象是老婆身份
                instance.getMarryMap().remove(marry.getHusbandId());
                instance.getMarryMap().put(fromQQ,qq);
                //发送结婚信息
                sentMistressMessage(event,qq,fromQQ,fromQQ);
            }
        } else {
            event.getGroup().sendMessage("当小三失败(NTR不得好死)...");
        }
        //添加小三列表
        if (!isTrue) instance.getXiaoSanList().add(fromQQ);
    }

    /**
     * 群老婆列表
     */
    public static void getWifeList(GroupMessageEvent event) {
        ShareData instance = ShareData.getInstance();
        Group group = event.getGroup();
        LinkedHashMap<Long, Long> map = instance.getMarryMap();
        if (map.isEmpty()){
            event.getGroup().sendMessage("今天还没有人娶老婆呢...");
            return;
        }
        ForwardMessageBuilder MessageBuilder = new ForwardMessageBuilder(event.getGroup());
        map.forEach((husBand,wife)->{
            NormalMember husBandMember = group.get(husBand);
            NormalMember wifeMember = group.get(wife);
            MessageBuilder.add(event.getBot(),(chain)->{
                chain.add(new PlainText(husBandMember!=null ? husBandMember.getNick() : String.valueOf(husBand)));
                chain.add(new PlainText(" 你的群老婆是-> "));
                chain.add(new PlainText(wifeMember!=null ? wifeMember.getNick() : String.valueOf(wife)));
                return null;
            });
        });
        ForwardMessage build = MessageBuilder.build();
        event.getGroup().sendMessage(build);
    }
    //喵服获取信息
    public synchronized static void getMiaoFuList(GroupMessageEvent event) {
        event.getGroup().sendMessage("获取服务器信息中...");
        ShareData instance = ShareData.getInstance();
        //获取需要的服务器的地址
        Map<String, String> addresses = instance.getAddresses();
        //克隆一个新的Map
        Map<String,String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : addresses.entrySet()) {
            if (entry.getKey().contains("喵服")) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
        }
        //获取服务器信息
        List<ServerEntry> projectZomboidList =CatApiUtil.getMessage(sortedMap);
        sendAddressMessage(projectZomboidList,sortedMap,event);
    }
    //奶服获取信息
    public static void getNaiFuList(GroupMessageEvent event) {
        event.getGroup().sendMessage("获取服务器信息中...");
        ShareData instance = ShareData.getInstance();
        //获取需要的服务器的地址
        Map<String, String> addresses = instance.getAddresses();
        //克隆一个新的Map
        Map<String,String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : addresses.entrySet()) {
            if (entry.getKey().contains("奶片")) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
        }
        //获取服务器信息
        List<ServerEntry> projectZomboidList = CatApiUtil.getMessage(sortedMap);
        sendAddressMessage(projectZomboidList,sortedMap,event);
    }

    public static void getLottery(GroupMessageEvent event) {
        //获取发送用户对象
        Member sender = event.getSender();
        //随机函数
        Random rand = new Random();
        int result = rand.nextInt(100);  // 生成0-99的随机数
        if (result>=50) {
            sender.mute(RandomUtil.RandomNumberByArray());
            event.getGroup().sendMessage("恭喜你获得一次禁言...");
        }else{
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://api.lolicon.app/setu/v2?r18=0")
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                JSONObject jsonObject = JSON.parseObject(response.body().string());
                String url = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("urls")
                        .getJSONObject(0).getString("original");
                MessageChain singleMessages = new MessageChainBuilder()
                        .append(new PlainText("恭喜你获得色图一张(15s后撤回)" +"\n"))
                        .append(new PlainText(url))
                        .build();
                MessageReceipt<Group> groupMessageReceipt = event.getGroup().sendMessage(singleMessages);
                //设置当前线程休眠10s
                Thread.sleep(15000);
                groupMessageReceipt.recall();
            }catch (Exception e){
                System.out.println("服务器通知失败!"+e);
            }
        }
    }

    public static void getServerList(GroupMessageEvent event, String serverName) {
        event.getGroup().sendMessage("获取"+serverName+"服务器信息中...");
        ShareData instance = ShareData.getInstance();
        //获取需要的服务器的地址
        Map<String, String> addresses = instance.getAddresses();
        //克隆一个新的Map
        Map<String,String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : addresses.entrySet()) {
            if (entry.getKey().contains(serverName)) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
        }
        List<ServerEntry> message = CatApiUtil.getMessage(sortedMap);
        sendCsgo2Message(message,sortedMap,event);
    }

    private static void sendCsgo2Message(List<ServerEntry> message, Map<String, String> sortedMap, GroupMessageEvent event) {
        if (message.isEmpty()){
            event.getGroup().sendMessage("暂无服务器信息");
            return;
        }
        //匹配服务器名称 修改服务器名称
        message.forEach(ServerEntry -> {
            //通过遍历sortedMap 的value 匹配 serverEntry的add
            sortedMap.forEach((key, value)->{
                if (value.equals(ServerEntry.getAddr())){
                    ServerEntry.setName(key);
                }
            });
        });
        File file = ImageUtil.imgBuilder(message);
        try {
            if (file != null) {
                FileInputStream fileInputStream = new FileInputStream(file);
                ExternalResource externalResource = ExternalResource.create(fileInputStream);
                Contact contact = event.getSubject();
                Image image = contact.uploadImage(externalResource);
                //发送信息
                event.getGroup().sendMessage(image);
            }
        } catch (Exception e) {
            System.out.println("服务器图片获取失败"+e.getMessage());
        }
    }

    public static void getServerOrder(GroupMessageEvent event,String Type) {
        try {
            ShareData instance = ShareData.getInstance();
            //处理参数
            String[] commands = Type.split(" ");
            //发起者QQ号
            Long fromQQ= event.getSender().getId();
            //群号ID
            Long groupId= event.getSender().getGroup().getId();
            //订阅列表
            List<ServerOrderEntry> serverOrderEntryList = instance.getServerOrderEntryList();
            //实体对象
            ServerOrderEntry serverOrderEntry =null;
            //获取群对象
            for (ServerOrderEntry order : serverOrderEntryList) {
                if (order.getGroupId().equals(groupId)){
                    serverOrderEntry =order;
                }
            }
            //获取群友
            if (serverOrderEntry == null){
                //添加群进配置文件
                serverOrderEntry = new ServerOrderEntry();
                serverOrderEntry.setGroupId(groupId);
                serverOrderEntry.setUserOrderList(new ArrayList<>());
                serverOrderEntryList.add(serverOrderEntry);
                instance.setServerOrderEntryList(serverOrderEntryList);
            }
            //获取操作用户
            List<UserOrderEntry> userOrderList = serverOrderEntry.getUserOrderList();
            //查看 userOrderList 里有没有 userId 等于 fromId的数据
            UserOrderEntry userOrderEntry = null;
            for (UserOrderEntry order : userOrderList) {
                if (order.getUserId().equals(fromQQ)) {
                    userOrderEntry = order;
                }
            }
            if (userOrderEntry == null){
                userOrderEntry = new UserOrderEntry();
                userOrderEntry.setUserId(fromQQ);
                userOrderEntry.setMapList(new ArrayList<>());
                userOrderEntry.setCommunityList(new ArrayList<>());
                userOrderEntry.setOrderTimeMap(new HashMap<>());
                userOrderList.add(userOrderEntry);
            }
            switch (commands[0]) {
                case "订阅添加":{
                    List<String> mapList = userOrderEntry.getMapList();
                    if (!mapList.contains(commands[1])) {
                        //获取所有地图
                        Map<String, MapEntry> map = CatApiUtil.getMap();
                        MapEntry mapEntry = map.get(commands[1].trim());
                        if (mapEntry != null) {
                            mapList.add(commands[1]);
                            event.getGroup().sendMessage("订阅成功");
                        } else {
                            event.getGroup().sendMessage("地图库并未检索到此张地图,请联系管理员,或前往https://www.bluearchive.top/map查看。");
                            return;
                        }
                    } else {
                        event.getGroup().sendMessage("您已经订阅过该地图了");
                    }
                    break;
                }
                case "订阅删除":{
                    List<String> mapList = userOrderEntry.getMapList();
                    if (mapList == null || mapList.isEmpty()) {
                        event.getGroup().sendMessage("您未订阅任何地图");
                        return;
                    }
                    if (mapList.contains(commands[1])) {
                        mapList.remove(commands[1]);
                        event.getGroup().sendMessage("删除成功");
                    } else {
                        event.getGroup().sendMessage("未查询到该地图");
                    }
                    break;
                }
                case "清空订阅":{
                    List<String> mapList = userOrderEntry.getMapList();
                    if (mapList == null || mapList.isEmpty()) {
                        event.getGroup().sendMessage("您未订阅任何地图");
                        return;
                    }
                    mapList.clear();
                    event.getGroup().sendMessage("清空成功");
                    break;
                }
                case "社区偏好":{
                    if (commands[1].equals("添加")){
                        switch (commands[2]){
                            case "exg":{
                                if (userOrderEntry.getCommunityList().contains("1")){
                                    event.getGroup().sendMessage("你已添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().add("1");
                                event.getGroup().sendMessage("添加成功");
                                break;
                            }
                            case "ub":{
                                if (userOrderEntry.getCommunityList().contains("2")){
                                    event.getGroup().sendMessage("你已添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().add("2");
                                event.getGroup().sendMessage("添加成功");
                                break;
                            }
                            case "zed":{
                                if (userOrderEntry.getCommunityList().contains("3")){
                                    event.getGroup().sendMessage("你已添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().add("3");
                                event.getGroup().sendMessage("添加成功");
                                break;
                            }
                            case "fys":{
                                if (userOrderEntry.getCommunityList().contains("4")){
                                    event.getGroup().sendMessage("你已添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().add("4");
                                event.getGroup().sendMessage("添加成功");
                                break;
                            }
                            case "93x":{
                                if (userOrderEntry.getCommunityList().contains("5")){
                                    event.getGroup().sendMessage("你已添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().add("5");
                                event.getGroup().sendMessage("添加成功");
                                break;
                            }
                            default:{
                                event.getGroup().sendMessage("请输入正确的社区名称[exg,ub,zed,fys,93x]");
                            }
                        }
                    }else if (commands[1].equals("删除")){
                        switch (commands[2]){
                            case "exg":{
                                if (!userOrderEntry.getCommunityList().contains("1")){
                                    event.getGroup().sendMessage("你未添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().remove("1");
                                event.getGroup().sendMessage("删除成功");
                                break;
                            }
                            case "ub":{
                                if (!userOrderEntry.getCommunityList().contains("2")){
                                    event.getGroup().sendMessage("你未添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().remove("2");
                                event.getGroup().sendMessage("删除成功");
                                break;
                            }
                            case "zed":{
                                if (!userOrderEntry.getCommunityList().contains("3")){
                                    event.getGroup().sendMessage("你未添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().remove("3");
                                event.getGroup().sendMessage("删除成功");
                                break;
                            }
                            case "fys":{
                                if (!userOrderEntry.getCommunityList().contains("4")){
                                    event.getGroup().sendMessage("你未添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().remove("4");
                                event.getGroup().sendMessage("删除成功");
                                break;
                            }
                            case "93x":{
                                if (!userOrderEntry.getCommunityList().contains("5")){
                                    event.getGroup().sendMessage("你未添加过该社区");
                                    return;
                                }
                                userOrderEntry.getCommunityList().remove("5");
                                event.getGroup().sendMessage("删除成功");
                                break;
                            }
                            default:{
                                event.getGroup().sendMessage("请输入正确的社区名称[exg,ub,zed,fys,93x]");
                            }
                        }
                    }
                    break;
                }
                case "订阅列表":{
                    List<String> mapList = userOrderEntry.getMapList();
                    if (mapList.isEmpty()) {
                        event.getGroup().sendMessage("您未订阅任何地图");
                        return;
                    }
                    //获取所有地图
                    Map<String, MapEntry> map = CatApiUtil.getMap();
                    //构建消息链
                    MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
                    Contact contact = event.getSubject();
                    for (String item : mapList) {
                        MapEntry mapEntry = map.get(item.trim());
                        if (mapEntry != null) {
                            messageChainBuilder.append("地图名 : ").append(item).append("\n");
                            messageChainBuilder.append("地图译名 : ").append(mapEntry.getLabel()).append("\n");
                            if (mapEntry.getMapUrl() != null) {
                                InputStream inputStream=null;
                                try {
                                    URL url = new URL(mapEntry.getMapUrl());
                                    inputStream = url.openConnection().getInputStream();
                                    Image image = ExternalResource.uploadAsImage(inputStream, contact);
                                    messageChainBuilder.append(image);
                                }catch (Exception e){
                                    System.out.println("网络图片获取失败!"+e);
                                }finally {
                                    if (inputStream!=null){
                                        inputStream.close();
                                    }
                                }
                            }
                        } else {
                            messageChainBuilder.append("地图名 : ").append(item).append("\n");
                        }
                    }
                    List<String> communityList = userOrderEntry.getCommunityList();
                    if (!communityList.isEmpty()) {
                        messageChainBuilder.append("社区偏好 : ");
                        for (String item : communityList) {
                            switch (item) {
                                case "1":
                                    messageChainBuilder.append("[EXG社区]");
                                    break;
                                case "2":
                                    messageChainBuilder.append("[UB社区]");
                                    break;
                                case "3":
                                    messageChainBuilder.append("[ZED社区]");
                                    break;
                                case "4":
                                    messageChainBuilder.append("[FYS社区]");
                                    break;
                                case "5":
                                    messageChainBuilder.append("[93X社区]");
                                    break;
                            }
                        }
                        messageChainBuilder.append("\n");
                    }
                    event.getGroup().sendMessage(messageChainBuilder.build());
                    break;
                }
                case "清空群订阅":{
                    //删除本群下所有群友的订阅(需要判断发起消息者是不是群主)
                    MemberPermission permission = event.getGroup().get(fromQQ).getPermission();
                    if (permission.getLevel() == MemberPermission.OWNER.getLevel()){
                        serverOrderEntry.setUserOrderList(new ArrayList<>());
                        event.getGroup().sendMessage("清空成功!");
                    }else{
                        event.getGroup().sendMessage("狗群友,你也敢清空群订阅?");
                    }
                    break;
                }
                case "指令列表":{
                    //构建消息链
                    MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
                    messageChainBuilder.append("=======地图订阅指南=======" + "\n");
                    messageChainBuilder.append("订阅添加 地图名(英文) 添加订阅地图" +"\n");
                    messageChainBuilder.append("订阅删除 地图名(英文) 删除订阅地图");
                    messageChainBuilder.append("订阅列表 查询自己订阅了那些地图"+"\n");
                    messageChainBuilder.append("订阅列表 查询自己订阅了那些地图"+"\n");
                    messageChainBuilder.append("清空订阅 清空自己所有订阅的地图"+"\n");
                    messageChainBuilder.append("社区偏好 添加 ['zed','exg','ub','fys','93x'] 地图订阅推送社区(只推送你添加的社区,默认未全部社区)"+"\n");
                    messageChainBuilder.append("社区偏好 删除 ['zed','exg','ub','fys','93x'] 地图订阅推送社区(只推送你添加的社区,默认为全部社区)"+"\n");
                    messageChainBuilder.append("清空群订阅 清空群友所有的订阅 (群主可用)"+"\n");
                    messageChainBuilder.append("地图信息查阅请前往 https://www.bluearchive.top/map"+"\n");
                    messageChainBuilder.append("=======服务器信息查询=======" + "\n");
                    messageChainBuilder.append("exg/ub/zed/fys/93x/ze" +"\n");
                    messageChainBuilder.append("=======群老婆指南=======" + "\n");
                    messageChainBuilder.append("娶群友 从群里随机选取一位今天有发言的群友作老婆" +"\n");
                    messageChainBuilder.append("离婚 和你的老婆离婚");
                    messageChainBuilder.append("订婚@某人 当@的那个人的老公"+"\n");
                    messageChainBuilder.append("当小三@某人 当@的那个人的老婆/老公"+"\n");
                    messageChainBuilder.append("群老婆列表 查看婚介所所有情侣信息"+"\n");
                    messageChainBuilder.append("=======禁言抽奖(付费功能)=======" + "\n");
                    messageChainBuilder.append("自动撤回 (视频,聊天记录,转发,音频)" +"\n");
                    messageChainBuilder.append("抽奖 随机获取禁言大礼包" + "\n");
                    messageChainBuilder.append("自动撤回 (视频,聊天记录,转发,音频)" +"\n");
                    messageChainBuilder.append("图片检测 自动撤回群友发的色图(可带禁言) 并将证据保留转发给群主" +"\n");
                    event.getGroup().sendMessage(messageChainBuilder.build());
                    break;
                }
            }
            FileWriter writer = new FileWriter(instance.getResolveConfigMapFile().getPath());
            String jsonString = JSON.toJSONString(instance.getServerOrderEntryList());
            writer.write(jsonString);
            writer.close();
        }catch (Exception e){
            event.getGroup().sendMessage("操作失败");
        }
    }
}
